// 文件路径：src/main/java/com/example/task/DeadlineAlertTask.java
package com.campus.task;

import com.alibaba.fastjson.JSON;
import com.campus.mapper.HomeworkMapper;
import com.campus.mapper.UserCourseMapper;
import com.campus.mapper.UserMapper;
import com.campus.pojo.entity.Homework;
import com.campus.service.HomeworkService;
import com.campus.websocket.WebSocketService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 作业截止提醒定时任务
 */
@Component
@Slf4j
public class DeadlineAlertTask {

    @Autowired
    private WebSocketService webSocketService;
    @Autowired
    private HomeworkMapper homeworkMapper;
    @Autowired
    private UserCourseMapper userCourseMapper;

    // 用于记录已提醒的作业ID，防止重复提醒（实际可存 Redis）
    private static final Set<Long> alertedHomeworkIds = ConcurrentHashMap.newKeySet();

    /**
     * 每隔5分钟执行一次：检查24小时内即将截止的作业
     */
    @Scheduled(fixedDelay = 1 * 60 * 1000)
    public void checkDeadlineAlert() {
        log.info("开始定时检查24小时以内截止且状态为已发布的作业... ");

        LocalDateTime now = LocalDateTime.now();
        LocalDateTime threshold = now.plusHours(24);

        // 查询所有状态为已发布的作业，且截止时间小于24小时的作业
        List<Homework> urgentHomeworkList = homeworkMapper.getUrgentHomeworkList(threshold);

        // 遍历作业列表
        for (Homework hw : urgentHomeworkList) {
//            if (alertedHomeworkIds.contains(hw.getId())) continue;

            // 获取作业对应的学生ID列表
            List<Long> userIds = userCourseMapper.selectStudentIdsByCourseId(hw.getCourseId());


            //包装json 数据
            Map<String, Object> map = new HashMap<>();
            map.put("homeworkId", hw.getId());
            map.put("message", "🔔 作业截止提醒：《" + hw.getTitle() + "》将在24小时内截止，请及时提交！");
            map.put("type", 1); //type=1 表示作业截止提醒 type=2 表示作业发布提醒
            String json = JSON.toJSONString(map);

            // 一次性群发
            webSocketService.sendMessageToUsers(userIds, json);

            // 记录已提醒的作业ID 防止重复提醒
            // alertedHomeworkIds.add(hw.getId());

            log.info("已向课程 {} 的 {} 名学生用户推送作业《{}》的截止提醒", hw.getCourseId(), userIds.size(), hw.getTitle());
        }
    }

    /**
     * 可选：每天凌晨清空提醒记录（避免 Set 越来越大）
     * 每天 00:00 执行
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void clearAlertedRecords() {
        int size = alertedHomeworkIds.size();
        alertedHomeworkIds.clear();
        System.out.println("已清空提醒记录，共清除 " + size + " 条");
    }
}